/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Carousel.js
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-05-30
 */
qui(
    function (require, exports, module) {
        Carousel.Util = $.extend(true, {}, EpgWeb.Util, {
            formatter: {
                qipuId: function (cellvalue, options, rowObject) {
                    var plusUrl = EpgWeb.urlConfig.getQiPuBaseUrl(rowObject.qipuId);
                    return "<a target='_blank' href='" + plusUrl + "' >" + rowObject.qipuId + "</a>";
                },
                albumId: function (cellvalue, options, rowObject) {
                    if (cellvalue > 0) {
                        var plusUrl = "http://lego.iqiyi.com/apis/search/search-area?filter_EQL_entityId=" + cellvalue + "&t=1";
                        return "<a target='_blank' href='" + plusUrl + "' >" + cellvalue + "</a>";
                    } else {
                        return "";
                    }
                },
                wrapColor: function (rowObject, value) {
                    if (rowObject.hintMsgObj == null) {
                        console.log("rowObject.hintMsgObj is null" + rowObject.qipuId)
                        return value;
                    }
                    if (rowObject.hintMsgObj.missPPSClient || rowObject.hintMsgObj.missQIYIClient) {
                        return  '<span style="color:red;">' + value + '</span>';
                    } else if (rowObject.hintMsgObj.missPPSRegion || rowObject.hintMsgObj.missQIYIRegion) {
                        return  '<span style="color:#ffa800;">' + value + '</span>';
                    }
                    return value
                },
                qipuIdNew: function (cellvalue, options, rowObject) {
                    var plusUrl = EpgWeb.urlConfig.getQiPuBaseUrl(cellvalue);
                    var colorPart = $("<em>&nbsp;&nbsp;</em>");
                    var currentClient = EpgWeb.Util.formatDateTimeFormat(new Date());
                    if (currentClient >= rowObject.startPlayTime && currentClient <= rowObject.endPlayTime) {
                        colorPart.addClass("current");
                    } else {
                        if (rowObject.startPlayTime.substr(11) >= "12:00:00") {
                            colorPart.addClass("afternoon");
                        } else {
                            colorPart.addClass("morning");
                        }
                    }
                    var cellEnd = cellvalue < 1 ? cellvalue : "<a target='_blank' href='" + plusUrl + "'>" + cellvalue + "</a>"
                    return  colorPart.prop("outerHTML") + cellEnd;
                },
                pnameNew: function (cellvalue, options, rowObject) {
                    var retValue = cellvalue;
                    if (rowObject.pageUrl != null) {
                        retValue = "<a target='_blank' href='" + rowObject.pageUrl + "'>" + cellvalue + "</a>";
                    }
                    if (rowObject.qipuId == 0 && rowObject.live == 1 && retValue.indexOf("delete") != -1) {
                        retValue = "<span style='color: red'>" + retValue + "</span>"
                    }
                    return retValue;
                },
                publishStatus: function (checkValue) {
                    if (checkValue == null)
                        return "";
                    checkValue = checkValue + "";
                    switch (checkValue) {
                        case "0":
                            return "未发布";
                        case "1":
                            return "已发布";
                        case "2":
                            return "页面下线";
                        case "3":
                            return "页面备用"
                        default:
                            return checkValue + "";
                    }
                },

                bossStatus_rule: function (cellvalue, options, rowObject) {
                    if (rowObject.qipuId % 100 == 2) {
                        return "";
                    }
                    if (cellvalue == 1) {
                        return "免费";
                    } else if (cellvalue == 2) {
                        return  "收费";
                    }
                },
                copyrightEndTime: function (checkValue) {
                    if (checkValue == null) {
                        return "";
                    }
                    if (typeof( checkValue ) == "string") {
                        return checkValue;
                    }
                    if (checkValue <= 0) {
                        return "---";
                    } else {
                        var date = new Date();
                        date.setTime(parseInt(checkValue))
                        return  Carousel.Util.formatDateTimeFormat(date);
                    }
                },
                purchase: function (checkValue) {
                    if (checkValue == null)
                        return "";
                    switch (checkValue) {
                        case 0:
                        case -100:
                            return "免费";
                        case 1:
                        case 2:
                            return "收费";
                        default:
                            return checkValue + ""
                    }
                },
                referContentType: function (cellvalue, options, rowObject) {
                    if (cellvalue == null) {
                        return ""
                    }
                    var response = Carousel.Dao.getContentType();
                    var ret = cellvalue;
                    $.each(response.data, function (index, element) {
                        if (cellvalue == element.val) {
                            ret = element.descr;
                            return true;
                        }
                    })
                    return ret;
                },
                playStatus: function (cellvalue, options, rowObject) {
                    if (cellvalue == null) {
                        return "Not exist ";
                    }
                    switch (cellvalue) {
                        case -1:
                            return "未设定";
                        case 0:
                            return "未开始";
                        case 1:
                            return "直播中";
                        case 2:
                            return "回看中";
                        case 3:
                            return "回看结束";
                        default :
                            return "Not exist value:" + cellvalue;
                    }
                    return cellvalue;
                },
                bossStatus: function (cellvalue, options, rowObject) {
                    var enumValue = "";
                    switch (cellvalue) {
                        case "FREE":
                            enumValue = "免费";
                            break;
                        case "PAIED_NOT_AVAILABLE":
                            enumValue = "付费未划价";
                            break;
                        case "PAIED_AVAILABLE":
                            enumValue = "付费已划价";
                            break;
                        default:
                            break;
                    }
                    return enumValue;
                },
                type: function (cellvalue, options, rowObject) {
                    var ret = "";
                    var enumNameData = Carousel.Dao.liveProgramType();
                    $.each(enumNameData.data, function (index, element) {
                        if (cellvalue == element.key) {
                            ret = element.descr;
                            return true;
                        }
                    })
                    return ret
                },
                live: function (cellvalue, options, rowObject) {
                    if (cellvalue == 0) {
                        return "未设置"
                    } else if (cellvalue == 1) {
                        return "点播"
                    } else if (cellvalue == 2) {
                        return "直播"
                    }
                    return "";
                },
                hiddenData_list: function (cellvalue, options, rowObject) {
                    var data = {};
                    if (typeof rowObject.lockStatus == 'undefined') {
                        rowObject.lockStatus = 0;
                    }
                    data.lockStatus = rowObject.lockStatus;
                    return JSON.stringify(data);
                },
                hiddenData_carousel_episode: function (cellvalue, options, rowObject) {
                    var data = {};
                    data.id = rowObject.id;
                    data.qipuId = rowObject.qipuId;
                    data.fatherId = rowObject.fatherId;
                    data.currentExec = rowObject.currentExec;
                    data.status = rowObject.status;
                    return JSON.stringify(data);
                },
                operator: function (cellvalue, options, rowObject) {
                    var checkDate = new Date();
                    checkDate.setTime(checkDate.getTime() + 30 * 1000 * 60);
                    var checkTime = EpgWeb.Util.formatDateTimeFormat(checkDate);
                    var retOperation = [];
                    if (checkTime > rowObject.startPlayTime) {
                        retOperation.push("<a class='disabled'>编目</a>");
                        retOperation.push(Carousel.Util.getBroadcastControl(rowObject));
                        retOperation.push("<a class='disabled'>广告点</a>");
                        retOperation.push("<a class='disabled'>删除</a>");
                        if (rowObject.live != 2) {
                            retOperation.push("<a class='disabled'>上移</a>");
                            retOperation.push("<a class='disabled'>下移</a>");
                            if (rowObject.lockStatus == 1) {
                                retOperation.push("<a class='disabled'>解锁</a>");
                            } else {
                                retOperation.push("<a class='disabled'>锁定</a>");
                            }
                        }
                    } else {
                        retOperation.push("<a href='javascript:;' onclick='Carousel.Util.jumpListToEdit(" + rowObject.id + "," + rowObject.fatherId + ")'>编目</a>")
                        retOperation.push(Carousel.Util.getBroadcastControl(rowObject));
                        retOperation.push("<a href='javascript:;' onclick='Carousel.Util.modifyAdvert(" + rowObject.id + "," + rowObject.advertEnable + ")'>广告点</a>");
                        retOperation.push("<a href='javascript:;' onclick='Carousel.Util.delProgram(" + rowObject.id + ")'>删除</a>");
                        if (rowObject.live != 2) {
                            if (rowObject.lockStatus == 1) {
                                retOperation.push("<a class='disabled'>上移</a>");
                                retOperation.push("<a class='disabled'>下移</a>");
                                retOperation.push("<a href='javascript:;' onclick='Carousel.Util.programToggleLock(" + rowObject.id + "," + rowObject.fatherId + ", 0)'>解锁</a>");
                            } else {
                                retOperation.push("<a href='javascript:;' onclick='Carousel.Util.programMoveUp(" + rowObject.id + "," + rowObject.fatherId + ")'>上移</a>");
                                retOperation.push("<a href='javascript:;' onclick='Carousel.Util.programMoveDown(" + rowObject.id + "," + rowObject.fatherId + ")'>下移</a>");
                                retOperation.push("<a href='javascript:;' onclick='Carousel.Util.programToggleLock(" + rowObject.id + "," + rowObject.fatherId + ", 1)'>锁定</a>");
                            }
                        }
                    }
                    retOperation.push("<a href='javascript:;' onclick='Carousel.Util.openHistory(" + rowObject.id + ")'>详细</a>");
                    return retOperation.join("&nbsp;");
                },
//                advert_operator: function (cellvalue, options, rowObject) {
//                    var retOperation = "";
//                    retOperation += "<a href='javascript:;' onclick='Carousel.Util.modifyAdvert(" + rowObject.id + ")'>广告点</a>";
//                    retOperation += "<a href='javascript:;' onclick='Carousel.Util.moveAdvert(" + rowObject.id + ",-1)'>上移</a>  ";
//                    retOperation += "<a href='javascript:;' onclick='Carousel.Util.moveAdvert(" + rowObject.id + ",1)'>下移</a>  ";
//                    return retOperation
//                },
                showName: function (cellvalue, options, rowObject) {
                    if (rowObject.pageUrl != null && rowObject.pageUrl.length > 0) {
                        return "<a target='_blank' href='" + rowObject.pageUrl + "'>" + cellvalue + "</a>"
                    }
                    return cellvalue;
                },
                endTime: function (cellvalue, options, rowObject) {
                    if (rowObject.repeatedStatus == 1) {
                        return "------";
                    }
                    return cellvalue.substr(0, 10);
                },
                type_rule: function (cellvalue, options, rowObject) {
                    if (rowObject.qipuId % 100 == 1) {
                        return "专辑"
                    } else if (rowObject.qipuId % 100 == 2) {
                        return "播单"
                    }
                },
                followedStatus: function (cellvalue, options, rowObject) {
                    if (cellvalue == 1) {
                        return "是";
                    } else if (cellvalue == 2) {
                        return "否";
                    }
                },
                repeatedStatus: function (cellvalue, options, rowObject) {
                    if (cellvalue == 1) {
                        return "是";
                    } else if (cellvalue == 2) {
                        return "否";
                    }
                },
                currentDisplay: function (cellvalue, options, rowObject) {
                    var clientTime = new Date(rowObject.startTime.replace(/-/g, "/"));
                    var serverTime = new Date(rowObject.serverTime.replace(/-/g, "/"));
                    this.setZeroTime(clientTime);
                    this.setZeroTime(serverTime);
                    if (rowObject.totalNum == 0 || serverTime.getTime() < clientTime.getTime()) {
                        return "";
                    }
                    var minusDay = ( serverTime.getTime() - clientTime.getTime()) / 86400000;
                    var startRuleNum = minusDay * rowObject.followNum + rowObject.startNum;
                    var repeatFlag = rowObject.repeatedStatus == 1 && rowObject.totalNum == rowObject.actualNum
                    if (repeatFlag) {
                        while (startRuleNum > rowObject.totalNum) {
                            startRuleNum -= rowObject.totalNum;
                        }
                    }
                    if (startRuleNum > rowObject.totalNum) {
                        return ""
                    }
                    var retArr = [];
                    for (var i = 0; i < rowObject.followNum; i++) {
                        if (startRuleNum + i > rowObject.totalNum) {
                            if (repeatFlag) {
                                startRuleNum -= rowObject.totalNum;
                            } else {
                                break;
                            }
                        }
                        retArr.push(startRuleNum + i);
                    }
                    return retArr.join(",");
                },
                restDay: function (cellvalue, options, rowObject) {
                    if (rowObject.repeatedStatus == 1) {
                        return "------";
                    }
                    var checkTime = new Date(rowObject.serverTime.replace(/-/g, "/"));
                    var clientTime = new Date(rowObject.endTime.replace(/-/g, "/"));
                    this.setZeroTime(checkTime);
                    this.setZeroTime(clientTime);
                    var minusDay = (clientTime.getTime() - checkTime.getTime() ) / 86400000 + 1;
                    if (minusDay <= 0) {
                        return "结束";
                    } else if (minusDay < 4) {
                        return "<span style='color: red'>" + minusDay + "天</span>"
                    } else {
                        return minusDay + "天"
                    }
                },
                hiddenData_rule: function (cellvalue, options, rowObject) {
                    var expired = 0;
                    if (rowObject.repeatedStatus != 1) {
                        var checkTime = new Date(rowObject.serverTime.replace(/-/g, "/"));
                        var clientTime = new Date(rowObject.endTime.replace(/-/g, "/"));
                        this.setZeroTime(checkTime);
                        this.setZeroTime(clientTime);
                        var minusDay = (clientTime.getTime() - checkTime.getTime() ) / 86400000 + 1;
                        if (minusDay <= 0) {
                            expired = 1;
                        }
                    }
                    var data = {};
                    data.id = rowObject.id;
                    data.fatherId = rowObject.fatherId;
                    data.expired = expired;
                    return JSON.stringify(data);
                },
                operator_rule: function (cellvalue, options, rowObject) {
                    return "";
                    //  return "<a href='javascript:;' onclick='Carousel.Util.delAutomationRule(" + rowObject.id + "," + rowObject.fatherId + ")'>删除</a>  ";
                },
                operator_carousel_episode: function (cellvalue, options, rowObject) {
                    if (Carousel.Config.IS_RULE_RUNNING) {
                        return "<a class='disabled'>删除</a> ";
                    }
                    return "<a href='javascript:;' onclick='Carousel.Util.episodeBatchDel(" + rowObject.id + "," + rowObject.fatherId + ")'>删除</a>  ";
                },
                log_type: function (cellvalue, options, rowObject) {
                    var ret = "";
                    var enumNameData = Carousel.Dao.logType();
                    $.each(enumNameData.data, function (index, element) {
                        if (cellvalue == element.key) {
                            ret = element.descr;
                            return true;
                        }
                    })
                    return ret;
                },
                advertDuration: function (cellvalue, options, rowObject) {
                    if (cellvalue == null) {
                        return "";
                    } else if (cellvalue == 0) {
                        return "无";
                    } else {
                        var ret = Carousel.Util.formatDateTimeFormat(new Date(new Date(rowObject.startPlayTime.replace(/-/g, "/")).getTime() - cellvalue * 1000)) + "(" + cellvalue + "秒)"
                        return ret;

                    }
                },
                advertEnable: function (cellvalue, options, rowObject) {
                    if (cellvalue == null) {
                        return "";
                    } else if (cellvalue == 1) {
                        return "有";
                    } else {
                        return "无";
                    }
                },
                currentExec: function (cellvalue, options, rowObject) {
                    if (cellvalue == 0) {
                        return "否";
                    } else if (cellvalue == 1) {
                        return "是";
                    }
                },
                operator_automation_rule: function (cellvalue, options, rowObject) {
                    if (rowObject.status == 1) {
                        return "<a class='disabled'>删除</a>";
                    }
                    return "<a href='javascript:;' onclick='Carousel.Util.delAutomationRule(" + rowObject.id + "," + rowObject.fatherId + ")'>删除</a>  ";
                },
                status_automation_rule: function (cellvalue, options, rowObject) {
                    switch (cellvalue) {
                        case 1:
                            return "启动";
                        case 0:
                            return "未启动";
                        case -1:
                            return "删除";
                        default :
                            return "unknown value:" + cellvalue;
                    }
                },
                publishStatus_automation_rule: function (cellvalue, options, rowObject) {
                    if (cellvalue == 1) {
                        return "未发布";
                    } else if (cellvalue == 2) {
                        return  "已发布";
                    } else {
                        return "未知数值：" + cellvalue;
                    }
                },
                twProgramName: function(cellvalue, options, rowObject) {
                   if(cellvalue == '') {
                       return rowObject.programName;
                   } else {
                       return '' + cellvalue;
                   }
                },

                twChannelName: function(cellvalue, options, rowObject) {
                    var val = null;

                    if(cellvalue == '') {
                        val = rowObject.channelName;
                    } else {
                        val = cellvalue;
                    }

                    return Carousel.Util.formatter.wrapColor(rowObject, val);

                },

                twAlbumName: function(cellvalue, options, rowObject) {
                    if(cellvalue == '') {
                        return rowObject.albumName;
                    } else {
                        return '' + cellvalue;
                    }
                },
            },
            episodeBatchDel: function (entityId, fatherId) {
                Carousel.Dao.episodeBatchDel({ids: "[" + entityId + "]", channelId: fatherId}, function (data) {
                    if (data != null && data.msg != null) {
                        SystemDialog.queryAlert(data.msg);
                    } else {
                        console.log("callbackHandler no return data");
                    }
                    $("#list").trigger("reloadGrid")
                });
            },


            getBroadcastControl: function (rowObj) {
                var hasStream = null != rowObj.channelHasStream && rowObj.channelHasStream == 1;
                if (hasStream) {
                    return "<a href='javascript:;' onclick='Carousel.Util.jumpToBroadcast(" + rowObj.id + "," + rowObj.fatherId + ")'>播控中心</a>";
                } else {
                    return "<a class='disabled'>播控中心</a>";
                }
            },
            jumpToBroadcast: function (entityId, fatherId) {
                var openUrl = "broadcast_manager_episode.html?programId=" + entityId + "&id=" + fatherId;
                window.open(openUrl);
            },
            jumpListToEdit: function (entityId, fatherId) {
                var openUrl = "program_edit.html?id=" + entityId + "&from=carousel&fatherId=" + fatherId;
                window.open(openUrl);
            },
            decodePlayPlatform: function (elementChild) {
                var locationControl = null;
                var platformObject = {platName: null, locationArr: []}
                platformObject.platName = elementChild["play_platform"];
                platformObject.status = 'online';
                if (elementChild["default_control"] != null) {
                    if ("ONLINE" != elementChild["default_control"]["availabe_status"]) {
                        platformObject.status = "offline";
                    }
                }
                if ($.isArray(elementChild["region_control"])) {
                    $.each(elementChild["region_control"], function (indexRegion, regionElement) {
                        if ($.isArray(regionElement["location"])) {
                            $.each(regionElement["location"], function (j, child) {
                                if (child.hasOwnProperty("province_id")) {
                                    if (child["province_id"] != 95 && child["province_id"] != 148 && child["province_id"] != 228) {
                                        locationControl = regionElement["location_control"];
                                        if (locationControl != null && "ONLINE" != locationControl["availabe_status"]) {
                                            platformObject.locationArr.push(child["province_id"]);
                                            console.log("break regionElement location");
                                        }
                                    }
                                }
                            })
                        }
                    })
                }
                return platformObject;
            },
            template: {
                albumSuggest: function (itemArr) {
                    return   '<div class="contract-item" >' +
                        '<span class="contract-width100" style="word-break:break-all">' + itemArr[0] + '</span>' +
                        '<span class="contract-width150" style="word-break:break-all">' + itemArr[1] + '</span>' +
                        '<span class="contract-width60" style="word-break:break-all">' + itemArr[2] + '</span>' +
                        '<span class="contract-width120" style="word-break:break-all">' + itemArr[3] + '</span>' +
                        '<span class="contract-width80" style="word-break:break-all">' + itemArr[4] + '</span>' +
                        '<span class="contract-width80" style="word-break:break-all">' + itemArr[5] + '</span></div>'
                }
            },
            WeekManager: null,
            openNewHtml: function (url) {
                var el = document.createElement("a");
                document.body.appendChild(el);
                el.href = url;
                el.target = '_blank';
                el.click();
                document.body.removeChild(el);
            },
            reloadHandler: function (data, tableName) {
                if (data != null) {
                    EpgWeb.Plugin.showTips({content: data.msg, type: data.code == "A00000" ? "success" : "error"});
                    if (data.code == "A00000") {
                        tableName = tableName == null ? "#list" : tableName;
                        $(tableName).trigger("reloadGrid")
                    }
                } else {
                    console.log("callbackHandler no return data");
                }
            },
            delProgram: function (entityId) {
                Carousel.Dao.deleteProgramData({id: entityId }, function (data) {
                    Carousel.Util.reloadHandler(data);
                })
            },

            programMoveUp: function (entityId, fatherId) {
                var sendData = {fatherId: fatherId, id: entityId, flag: 1, operationDay: Carousel.Config.dateTime};
                Carousel.Dao.programMove(sendData, function (data) {
                    Carousel.Util.reloadHandler(data);
                });
            },
            programIndexMove: function (entityId, targetId) {
                var sendData = {id: entityId, aimId: targetId, dateTime: Carousel.Config.dateTime, channelId: Carousel.Dao.channelId};
                Carousel.Dao.programIndexMove(sendData, function (data) {
                    Carousel.Util.reloadHandler(data);
                })
            },

            programMoveDown: function (entityId, fatherId) {
                var sendData = {fatherId: fatherId, id: entityId, flag: 2, operationDay: Carousel.Config.dateTime};
                Carousel.Dao.programMove(sendData, function (data) {
                    Carousel.Util.reloadHandler(data);
                });
            },
            programToggleLock: function (entityId, fatherId, lockType) {
                var sendData = {fatherId: fatherId, id: entityId, lockType: lockType };
                Carousel.Dao.programToggleLock(sendData, function (data) {
                    Carousel.Util.reloadHandler(data);
                });
            },
            modifyAdvert: function (entityId, advertEnable) {
//                var channel = Carousel.Dao.getChannel();
//                if (channel.alternatePlayCollection == null || channel.alternatePlayCollection.length == 0) {
//                    SystemDialog.queryAlert("<span style='color: red'> 无法添加，请先为频道添加备播视频！</span><br>广告期间需要使用备播码流")
//                    return;
//                }
                Carousel.Dao.cfgName.ad_selected = entityId;
                $("#advert_dlg").dialog("open");
//                var durationData = Carousel.Dao.adDuration();
//                if(durationData != null){
//                    var referKey = 1;
//                    $.each( durationData.data , function (i,element){
//                        if(element.val == advertDuration){
//                            referKey = element.key;
//                            return true;
//                        }
//                    })
//                }
                $("input[name=advertEnable][value='" + advertEnable + "']").prop("checked", true)
            },
            moveAdvert: function (entityId, moveType) {

            },
            recordDuration: function (dataOriginl) {
                Carousel.Config.durationMap = [];
                if (dataOriginl == null || dataOriginl.length == 0) {
                    return;
                }
                $.each(dataOriginl, function (i, element) {
                    var makeUpData = {};
                    makeUpData.id = element.id
                    makeUpData.referQipuId = element.carouselEpisode;
                    makeUpData.isLive = element.live;
                    makeUpData.startPlayTime = new Date(element.startPlayTime.replace(/-/g, "/")).getTime()
                    makeUpData.endPlayTime = new Date(element.endPlayTime.replace(/-/g, "/")).getTime();
                    makeUpData.pname = element.pname;
                    if (makeUpData.isLive == 2) {
                        makeUpData.duration = makeUpData.endPlayTime - makeUpData.startPlayTime;
                    } else {
                        makeUpData.duration = element.duration == null ? 0 : element.duration * 1000;
                    }
                    Carousel.Config.durationMap.push(makeUpData);
                })
            },
            addBreakHint: function (dataOriginl, tableName) {
                if (tableName == null) {
                    tableName = "#list"
                }
                var aimGrid = $(tableName);
                if (dataOriginl == null || dataOriginl.length == 0) {
                    return;
                }
                $.each(Carousel.Config.durationMap, function (i, element) {
                    if (element.duration > element.endPlayTime - element.startPlayTime) {
                        aimGrid.setCell(element.id, "endPlayTime", '', {backgroundColor: "#FFFF00"});
                    }
                });
            },
            showNoResult: function (dataLength, tableName) {
                if (tableName == null) {
                    tableName = "#list"
                }
                var jqGridTarget = $(tableName);
                var parentElement = jqGridTarget.parent();
                if (parentElement.find(".norecords").html() == null) {
                    parentElement.append('<div class="norecords">没有符合数据</div>');
                    parentElement.find(".norecords").hide();
                }
                if (dataLength == 0) {
                    parentElement.find(".norecords").show();
                } else {
                    parentElement.find(".norecords").hide();
                }
            },
            fillLineNo: function (tableName) {
                if (tableName == null) {
                    tableName = "#list";
                }
                var _jqGrid = $(tableName);
                var params = _jqGrid.jqGrid("getGridParam");
                var index = (params.page - 1 ) * params.rowNum;
                var dataOriginal = _jqGrid.jqGrid("getDataIDs");
                $.each(dataOriginal, function (i, element) {
                    index++;
                    _jqGrid.setRowData(element, {"index": index });
                })
                console.log("更新行号");
            },
            toggleTwColumns: function (tableName) {
                if (tableName == null) {
                    tableName = "#list";
                }
                var _jqGrid = $(tableName);
                var channel = Carousel.Dao.getChannel();
                if (channel['type'] == 11) {
                    _jqGrid.hideCol(["programName", "albumName", "channelName"]).trigger("reloadGrid");
                }else{
                    _jqGrid.hideCol(["twProgramName", "twAlbumName", "twChannelName"]).trigger("reloadGrid");
                }

            },
            notifyChangeBtnStatus: function (tableName) {
                if (tableName == null) {
                    tableName = "#list";
                }
                var _jqGrid = $(tableName);
                var dataOriginal = _jqGrid.jqGrid("getDataIDs");
                $("button[name=btn_rule_start]").prop("disabled", "disabled");
                $("button[name=btn_rule_stop]").prop("disabled", "disabled");
                $("button[name=btn_rule_start]").hide();
                $("button[name=btn_rule_stop]").hide();
                if (dataOriginal == null) {
                    $("button[name=btn_rule_start]").show();
                    return;
                }
                if (dataOriginal.length == 0) {
                    $("button[name=btn_rule_start]").removeAttr("disabled");
                    $("button[name=btn_rule_start]").show();
                } else {
                    var checkData = _jqGrid.getRowData(dataOriginal[0]);
                    if (JSON.parse(checkData.hiddenData).status == 1) {
                        $("button[name=btn_rule_stop]").removeAttr("disabled");
                        $("button[name=btn_rule_stop]").show();
                    } else {
                        $("button[name=btn_rule_start]").removeAttr("disabled");
                        $("button[name=btn_rule_start]").show();
                    }
                }
            },


            checkSelectAble: function (dataOriginl, tableName) {
                if (tableName == null) {
                    tableName = "#list";
                }
                var _jqGrid = $(tableName);
                if (dataOriginl == null || dataOriginl.length == 0) {
                    return;
                }
//                var target = $("#cb_list");
//                target.unbind();
//                target.bind("click", this.mySelectedHandler);
                var currentDay = new Date();
                currentDay.setTime(currentDay.getTime() + 30 * 60 * 1000)
                var checkTime = Carousel.Util.formatDateTimeFormat(currentDay)
                $.each(dataOriginl, function (i, element) {
                    if (element.startPlayTime < checkTime) {
                        _jqGrid.find("input[type=checkbox][name=jqg_list_" + element.id + "]").prop("disabled", "disabled");
                        // $("#"+element.id).prop("disabled", "disabled");
                        //   _jqGrid.find("input[type=checkbox][name=jqg_list_"+element.id+"]").parent().find("td[aria-describedby=list_index]").unbind();
                    }

                });
            },
//            mySelectedHandler: function (event) {
//                var checkedFlag1 = $(event.currentTarget).prop("checked") == true;
//                var _jqGrid = $("#list");
//                var dataOriginl = Carousel.Dao.getFromCache("originalArr");
//                if (dataOriginl == null || dataOriginl.length == 0) {
//                    return;
//                }
//                var checkBoxArr = _jqGrid.find("input[type=checkbox][name^=jqg_list_]");
//                $.each(checkBoxArr, function (i, element) {
//                    if ($(element).prop("disabled") != true && $(element).prop("checked") != checkedFlag1) {
//                        _jqGrid.setSelection(dataOriginl[i].id, checkedFlag1);
//                    }
//                });
//                $(event.currentTarget).prop("checked", checkedFlag1)
//            },
            getAdvertStart: function (element) {

            },
            setColorTime: function (dataOriginl, tableName) {
                if (tableName == null) {
                    tableName = "#list";
                }
                var _jqGrid = $(tableName);
                if (dataOriginl == null || dataOriginl.length == 0) {
                    return;
                }
                var checkLength = dataOriginl.length - 1;
                var check2 = null;
                var makeStartColor = [];
                var makeEndColor = [];
                var makeMockColor = [];
                $.each(dataOriginl, function (i, element) {
                    if (element.qipuId == 0 && element.live == 1 && element.pname.indexOf("delete") == -1) {
                        makeMockColor.push(element.id);
                    }
                    if (i == checkLength) {
                        if (element.endPlayTime.length != 19 || "23:59:59" != element.endPlayTime.slice(-8)) {
                            if (element.endPlayTime.substr(0, 10) == element.startPlayTime.substr(0, 10)) {
                                makeEndColor.push(element.id);
                            }
                        }
                        return true;
                    }
                    check2 = dataOriginl[i + 1];
                    var checkDate1 = new Date(check2.startPlayTime).getTime() - check2.advertDuration * 1000;
                    var checkDate2 = new Date(element.endPlayTime).getTime();
                    var checkDate3 = Carousel.Util.formatDateTimeFormat(new Date(new Date(element.startPlayTime).getTime() - element.advertDuration * 1000));
                    if (checkDate2 > checkDate1) {
                        makeEndColor.push(element.id);
                        makeStartColor.push(check2.id);
                    } else if (checkDate1 > checkDate2) {
                        makeStartColor.push(check2.id);
                    }
                    if (Carousel.Dao.cfgName.yesterdayEndTime > element.endPlayTime) {
                        makeEndColor.push(element.id);
                        makeStartColor.push(element.id);
                    } else if (Carousel.Dao.cfgName.yesterdayEndTime > checkDate3) {
                        makeStartColor.push(element.id);
                    }
                });
                if (makeMockColor.length > 0) {
                    var dealArr = [];
                    $.each(makeMockColor, function (i, elementId) {
                        _jqGrid.setCell(elementId, "startPlayTime", '', {color: "#00cccc"});
                        _jqGrid.setCell(elementId, "endPlayTime", '', {color: "#00cccc"})
                    })
                }

                if (makeStartColor.length > 0) {
                    $.each(makeStartColor, function (i, elementId) {
                        _jqGrid.setCell(elementId, "startPlayTime", '', {color: "#ff0000"});
                    })
                }
                if (makeEndColor.length > 0) {
                    $.each(makeEndColor, function (i, elementId) {
                        _jqGrid.setCell(elementId, "endPlayTime", '', {color: "#ff0000"});
                    })
                }
            },

            tranDurationFormat: function (duration) {
                var darArr = [];
                darArr.push(duration % 60);
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 60);
                }
                duration = ( duration - duration % 60) / 60;
                if (duration > 0) {
                    darArr.push(duration % 24);
                }
                duration = ( duration - duration % 24) / 24;
                if (duration > 0) {
                    darArr.push(duration);
                }
                var retValue = "";
                switch (darArr.length) {
                    case 4:
                        retValue = darArr[3] + "天";
                    case 3:
                        retValue += darArr[2] + "时";
                    case 2:
                        retValue += darArr[1] + "分";
                    case 1:
                        retValue += darArr[0] + "秒";
                        break;
                }
                return retValue;
            },

            getSearchParamsBySettings: function () {
                var response = Carousel.Dao.getPlatSettings();
                if (response == null) {
                    console.log("setting error");
                    return {};
                }
                var entity = response.data;
                var params = {};
                if (entity.checkPublishType == 1) {
                    params["filter_EQI_pagePublishStatus"] = 1;
                }
                if (entity.checkCopyRightType == 1) {
                    params["filter_GTI_copyrightOwnerId"] = 0;
                }
                if (entity.checkBossType == 0) {
                    params["filter_INI_isPurchase"] = "0,-100";
                } else if (entity.checkBossType == 1) {
                    params["filter_INI_isPurchase"] = "1,2";
                }
                var platformTypeResponse = Carousel.Dao.getPlatformType();
                $.each(platformTypeResponse.data, function (i, element) {
                    //   params["region_" + element.val] = 0;
                    if (entity.regionLimitArr.indexOf(parseInt(element.key)) != -1) {
                        params["region_" + element.val] = 1;
                    }
                });
                var platformReferResponse = Carousel.Dao.getPlatformRefer();
                $.each(platformReferResponse.data, function (i, element) {
                    //   params["filter_EQI_" + element.val] = 0;
                    if (entity.onlineLimitArr.indexOf(parseInt(element.key)) != -1) {
                        params["filter_EQI_" + element.val] = 1;
                    }

                });
                console.log(" params:" + JSON.stringify(params))
                return params;
            },
            checkMultiCallBack: function (data, bindModel) {
                Carousel.Config.BIND_BATCH_ADD_MODEL = bindModel;
                console.log("checkMultiCallBack wait to do" + JSON.stringify(data));
                var result = data.result;
                var multiArr = [];
                var hasUsedArr = [];
                $.each(result, function (i, element) {
                    if (element.carouselEpisode > 0) {
                        hasUsedArr.push(element.carouselEpisode);
                    }
                });
                $.each(Carousel.Config.saveIds, function (i, element) {
                    if (hasUsedArr.indexOf(element) != -1) {
                        multiArr.push(element);
                    }
                });

                var hintMsg = [];
                if (Carousel.Config.invalidArr != null && Carousel.Config.invalidArr.length > 0) {
                    $.each(Carousel.Config.invalidArr, function (i, element) {
                        var idIndex = Carousel.Config.saveIds.indexOf(element);
                        if (idIndex != -1) {
                            Carousel.Config.saveIds.splice(idIndex, 1);
                        }
                        hintMsg.push(+"节目奇谱ID:<span style='color: red'>" + element + "</span>没有奇谱数据！");
                    })
                }
                if (multiArr != null && multiArr.length > 0) {
                    $.each(multiArr, function (i, element) {
                        hintMsg.push("节目奇谱ID:<span style='color: red'>" + element + "</span>,重复！");
                    })
                }
                // var dataArr = $("#listAdd1").jqGrid('getData');
                var responseData = Carousel.Dao.getFromCache("gridData1");
                var dataArr = responseData != null ? responseData.rows : [];
                var missPPSClientArr = [];
                var missPPSRegionArr = [];
                var missQIYIClientArr = [];
                var missQIYIRegionArr = [];
                $.each(dataArr, function (i, element) {
                    if (Carousel.Config.saveIds.indexOf(element.qipuId) != -1) {
                        if (element.hintMsgObj.missPPSClient === true) {
                            missPPSClientArr.push(element.qipuId);
                        }
                        if (element.hintMsgObj.missPPSRegion === true) {
                            missPPSRegionArr.push(element.qipuId);
                        }
                        if (element.hintMsgObj.missQIYIClient === true) {
                            missQIYIClientArr.push(element.qipuId);
                        }
                        if (element.hintMsgObj.missQIYIRegion === true) {
                            missQIYIRegionArr.push(element.qipuId);
                        }
                    }
                })
                var remindLength = 0;
                var checkMsgArr = [ missPPSClientArr, missPPSRegionArr, missQIYIClientArr , missQIYIRegionArr ];
                var platformCheck = [Carousel.Config.Hint.PPS_CLIENT_HINT , Carousel.Config.Hint.PPS_REGION_HINT, Carousel.Config.Hint.QIYI_CLIENT_HINT, Carousel.Config.Hint.QIYI_REGION_HINT];
                var platformMsg = [];
                $.each(checkMsgArr, function (i, checkArr) {
                    if (checkArr.length > 0) {
                        remindLength = checkArr.length;
                        if (remindLength > 3) {
                            checkArr.length = 3;
                            platformMsg.push("节目奇谱ID " + checkArr.join(",") + "等" + remindLength + "个节目" + platformCheck[i]);
                        } else {
                            platformMsg.push("节目奇谱ID " + checkArr.join(",") + platformCheck[i]);
                        }
                    }
                })
                if (platformMsg.length > 0) {
                    platformMsg.push(Carousel.Config.Hint.QUERY_ADD);
                }
                hintMsg = hintMsg.concat(platformMsg);
                if (hintMsg.length > 0) {
                    $("#batchResponseDiv").find("div[sign=detail]").html(hintMsg.join("<br>"));
                    $("#batchResponseDiv").dialog("open");
                } else {
                    this.batchAddByBindModel()
                }
            },
            removeDisAble: function () {
                $("button[name=btn_addType1]").removeAttr("disabled");
                $("button[name=btn_addType2]").removeAttr("disabled");
                $("button[name=btn_addType3]").removeAttr("disabled");
            },
            addDisAble: function () {
                $("button[name=btn_addType1]").attr("disabled", "disabled");
                $("button[name=btn_addType2]").attr("disabled", "disabled");
                $("button[name=btn_addType3]").attr("disabled", "disabled");
            },
            addLibraryDisAble: function () {
                $("button[name=btn_rule_start]").attr("disabled", "disabled");
                $("button[name=btn_rule_stop]").attr("disabled", "disabled");
            },
            removeLibraryDisAble: function () {
                $("button[name=btn_rule_start]").removeAttr("disabled");
                $("button[name=btn_rule_stop]").removeAttr("disabled");
            },

            batchAdd: function () {
                if (Carousel.Config.saveIds == null) {
                    console.log("saveIds is empty");
                    return;
                }
                Carousel.Util.addDisAble();
                console.log("sendId" + JSON.stringify(Carousel.Config.saveIds));
                Carousel.Dao.batchAdd({data: JSON.stringify(Carousel.Config.saveIds), beginTime: Carousel.Config.dateTime, fatherId: Carousel.Dao.channelId }, function (data) {
                    Carousel.Util.removeDisAble();
                    if (data != null) {
                        if (data.code == "A00000") {
                            EpgWeb.Plugin.showTips({content: data.msg});

                            $("#cb_listAdd1").click();
                            if ($("#cb_listAdd1").prop("checked") == true) {
                                $("#cb_listAdd1").click()
                            }
                        } else {
                            SystemDialog.queryAlert(data.msg);
                        }
                    } else {
                        console.log("data" + JSON.stringify(data));
                    }
                });
            },
            episodeBatchAdd: function () {
                if (Carousel.Config.saveIds == null) {
                    console.log("saveIds is empty");
                    return;
                }
                Carousel.Util.addDisAble();
                console.log("sendId" + JSON.stringify(Carousel.Config.saveIds));
                Carousel.Dao.episodeBatchAdd({data: JSON.stringify(Carousel.Config.saveIds), fatherId: Carousel.Dao.channelId }, function (data) {
                    Carousel.Util.removeDisAble();
                    if (data != null) {
                        if (data.code == "A00000") {
                            $("#cb_listAdd1").click();
                            if ($("#cb_listAdd1").prop("checked") == true) {
                                $("#cb_listAdd1").click()
                            }
                            $("#queryMessage").dialog("open");
                        } else {
                            var msg = data.msg == null ? "添加出现异常" : JSON.parse(data.msg).ret_msg;
                            EpgWeb.Plugin.showTips({content: msg, type: "error" });
                        }
                    } else {
                        console.log("data" + JSON.stringify(data));
                    }
                });
            },
            episodeIndexMove: function (entityId, targetId) {
                var sendData = {id: entityId, aimIdx: targetId, channelId: Carousel.Dao.channelId};
                Carousel.Dao.episodeIndexMove(sendData, function (data) {
                    Carousel.Util.reloadHandler(data);
                })
            },
            notifyRuleChangeStatus: function (execStatus, callback) {
                var data = { channelId: Carousel.Dao.channelId, execStatus: execStatus};
                Carousel.Dao.notifyRuleChangeStatus(data, function (data) {
                    if (data == null || data.code != "A00000") {
                        if (data.msg != null) {
                            SystemDialog.queryAlert(data.msg)
                        }
                    }

                    Carousel.Util.queryVirtualRule({ channelId: Carousel.Dao.channelId}, function (flag) {
                        console.log("notifyRuleChangeStatus callback wait to do ");
                        $("#list").trigger("reloadGrid")
                    });
                })

            },
            checkQipuPlatformControl: function (callback, ret) {
                var task = Carousel.Task.checkForQipuDataTask(Carousel.Util.multiCheckHandler);
                var dataArr = [];
                var requestData = null;
                var currentTime = Date.now();

                Carousel.Dao.putToCache("originalArr", ret.result);
                $.each(ret.result, function (i, element) {
                    requestData = {url: EpgWeb.urlConfig.getQiPuBaseUrl(element["qipuId"]), type: "get"};
                    dataArr.push({"request": JSON.stringify(requestData), timeSign: currentTime });
                });
                Carousel.Config.lockFlag = true;
                $("#loadLegoMessage").dialog("open");
                EpgWeb.ajaxQueue.batchRequest(task.regName, task.options, dataArr, task.handler);
                var timerId = setInterval(function () {
                    if (!Carousel.Config.lockFlag) {
                        clearInterval(timerId);
                        $("#loadLegoMessage").dialog("close");
                        callback(ret);
                    }
                }, 160)
                EpgWeb.ajaxQueue.startLoad();
            },
            multiCheckHandler: function (options) {
                console.log(options.acceptArr);
                var playControlArr = null;
                var checkPlatforms = Carousel.Dao.getPlatformType().data;
                var originalArr = Carousel.Dao.getFromCache("originalArr");
                $.each(options.acceptArr, function (i, element) {
                    var original = originalArr[element.nodeIndex ];
                    if (element.responseData == null) {
                        original.illegal = true;
                        return true;
                    }
                    playControlArr = element.responseData["access_play_control"];
                    if (null == playControlArr && ( null == element.responseData["available_status"] || "OFFLINE_COPYRIGHT" === element.responseData["available_status"])) {
                        original.illegal = true;
                        return true;
                    }
                    if ($.isArray(playControlArr)) {
                        var temp = {};
                        $.each(playControlArr, function (index, elementChild) {
                            var platformObject = Carousel.Util.decodePlayPlatform(elementChild);
                            if (platformObject.platName != null) {
                                temp[platformObject.platName] = platformObject;
                            }
                        })

                        original.controlObj = temp
                        var qipuPlatformData = [];
                        var qipuRegionData = [];
                        var hintMsgObj = {
                            missQIYIClient: false,
                            missPPSClient: false,
                            missQIYIRegion: false,
                            missPPSRegion: false
                        };
                        $.each(checkPlatforms, function (index, element) {
                            var ppsFlag = element.val.indexOf("PPS") !== -1;
                            if (!temp.hasOwnProperty(element.val) || temp[element.val].status != "online") {
                                qipuPlatformData.push(element.val)
                                if (ppsFlag) {
                                    hintMsgObj.missPPSClient = true;
                                } else {
                                    hintMsgObj.missQIYIClient = true;
                                }
                            }
                            if (temp.hasOwnProperty(element.val) && temp[element.val].locationArr.length > 0) {
                                qipuRegionData.push(element.val);
                                if (ppsFlag) {
                                    hintMsgObj.missPPSRegion = true;
                                } else {
                                    hintMsgObj.missQIYIRegion = true;
                                }
                            }
                        });
                        original["qipuPlatformData"] = qipuPlatformData;
                        original["qipuRegionData"] = qipuRegionData;
                        original["hintMsgObj"] = hintMsgObj;

                        console.log(element.responseData["id"] + "| qipuPlatformData : " + JSON.stringify(original["qipuPlatformData"]));
                        console.log(element.responseData["id"] + "| qipuRegionData: " + JSON.stringify(original["qipuRegionData"]));
                        console.log(element.responseData["id"] + "| hintMsgObj: " + JSON.stringify(original["hintMsgObj"]));
                    }

                    // TW
                    channelbase = Carousel.Dao.getChannel();
                    if(channelbase != null && channelbase['type'] == 11) {
                        localbaseArr = element.responseData['local_base'];
                        if(localbaseArr != null) {
                            $.each(localbaseArr, function(index, local) {
                                if(local['language'] == 'zh_TW' && local['display_name'] != null) {
                                    original['displayName'] = local['display_name'];
                                }
                            })
                        }
                    }

                });
                Carousel.Config.lockFlag = false;
            },

            isCarouselCheck: function (channelData) {
                if (channelData.liveType != 3) {
                    EpgWeb.Plugin.showTips({content: Carousel.Config.Hint.NOT_CAROUSEL, type: "error"});
                    setTimeout(function () {
                        window.location.href = "/epg/program_list.html?fatherId=" + channelData.id;
                    }, 2000)
                    return false;
                }
                return true;
            },

            //
            queryTotalNum: function (entityId, handler) {
                var params = Carousel.Util.getSearchParamsBySettings();
                params["filter_EQL_albumId"] = entityId;
                params["filter_GTL_qipuId"] = 0;
                params["filter_GEL_duration"] = 60000;
                params["filter_EQI_contentType"] = 1;
                params["t"] = 0;
                params["page.order"] = "asc,asc";
                params["page.orderBy"] = "videoOrder,createTime";
                params["page.pageSize"] = 50;
                params["page.pageNo"] = 1;

                var QueryComponent = {
                    referElement: Carousel.Config.ruleSelectElement,
                    totalCount: 0,
                    params: params,
                    query: function (entityId) {
                        var self = this;
                        var requestData = {url: Carousel.Constant.thirdUrl_apis_search_area_url, type: "get",
                            params: self.params,
                            needCookie: true};
                        var options = {
                            url: Carousel.urlConfig.redirect,
                            type: "post",
                            dataType: "json",
                            data: {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        }

                        $.ajax({
                            type: options.type,
                            url: options.url,
                            dataType: options.dataType,
                            beforeSend: function (request) {
                                request.setRequestHeader("Sign", "#f93Uc31K24()_@");
                            },
                            data: options.data,
                            success: function (data) {
                                self.totalCount += data.data.result.length;
                                if (true === data.data.hasNext) {
                                    self.params["page.pageNo"] = data.data.nextPage;
                                    self.query(entityId);
                                } else {
                                    $("input[name=actualNum]").val(self.totalCount);
                                    if (handler != null) {
                                        handler();
                                    }
                                }
                            },
                            error: function (data) {
                                EpgWeb.Plugin.showTips({
                                    content: "请求失败",
                                    type: "error"
                                })
                                $("input[name=actualNum]").val(0);
                            }});
                    }
                };
                QueryComponent.query(entityId);
            },
            transToCheckKey: function (sendData) {
                var dataArr = [];
                dataArr.push(sendData.qipuId);
                dataArr.push(sendData.startNum);
                dataArr.push(sendData.repeatedStatus);
                dataArr.push(sendData.followedStatus);
                dataArr.push(sendData.followNum);
                dataArr.push(sendData.startTime);
                return dataArr.join("|")
            },
            queryVirtualRule: function (data, callback) {
                Carousel.Util.addLibraryDisAble();
                Carousel.Dao.automationList(data, function (data) {
                    if (data != null && data.code == "A00000") {
                        Carousel.Config.IS_RULE_RUNNING = data.data.result.length > 0 && data.data.result[0].status == 1;
                        Carousel.Util.updateRuleStatusBtn(Carousel.Config.IS_RULE_RUNNING);
                        callback(true);
                    } else {
                        var msg = data != null ? data.msg : "";
                        EpgWeb.Plugin.showTips("初始化异常!" + msg);
                        callback(false);
                    }
                    Carousel.Util.removeLibraryDisAble();
                })
            },
            updateRuleStatusBtn: function (isRunning) {
                if (isRunning) {
                    $("button[name=btn_rule_start]").hide();
                    $("button[name=btn_rule_stop]").show();
                } else {
                    $("button[name=btn_rule_start]").show();
                    $("button[name=btn_rule_stop]").hide();
                }
            },
            openHistory: function (entityId) {
                Carousel.Dao.doAuthData({
                    url: '/epg/channel_log.html',
                    doSuccess: function () {
                        Carousel.Config.AUTH_LOG_DETAIL = true;
                    },
                    doFinal: function () {
                        var tableConfig = $.extend(true, {}, Carousel.Config.TABLE_LOG);
                        tableConfig.width = Carousel.Config.AUTH_LOG_DETAIL ? 875 : 425
                        var colModel = tableConfig.colModel;
                        var newColModel = [];
                        var colModelConfig = Carousel.Config.TABLE_COLMODEL_CONFIG;

                        $.each(colModel, function (i, model) {
                            newColModel.push(colModelConfig[model]);
                        });
                        tableConfig.colModel = newColModel;
                        tableConfig.colModel[4].hidden = !Carousel.Config.AUTH_LOG_DETAIL;
                        $('#logList').jqGrid(tableConfig);
                        $("#programLogDiv").dialog({
                            title: "历史记录",
                            autoOpen: false,
                            width: Carousel.Config.AUTH_LOG_DETAIL ? 900 : 450,
                            height: 600,
                            modal: true,
                            dialogClass: 'alert',
                            open: function () {
                                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                            }
                        });
                        $("#programLogDiv").dialog("open");
                        $('#logList').jqGrid('setGridParam', {
                            page: 1,
                            datatype: "json",
                            postData: {id: entityId}
                        }).trigger('reloadGrid');
                    }
                })
            },
            batchAddByBindModel: function () {
                if (Carousel.Config.BIND_BATCH_ADD_MODEL != null) {
                    console.log("BIND_BATCH_ADD_MODEL:" + Carousel.Config.BIND_BATCH_ADD_MODEL);
                    this[Carousel.Config.BIND_BATCH_ADD_MODEL]();
                }
            },
            // automation rule start
            delAutomationRule: function (entityId, fatherId) {
                Carousel.Dao.delAutomationRule({ids: entityId, fatherId: fatherId}, function (data) {
                    if (data != null && data.msg != null) {
                        SystemDialog.queryAlert(data.msg);
                    } else {
                        console.log("callbackHandler no return data");
                    }
                    $("#ruleList").trigger("reloadGrid")
                });
            },
            batchDelAutomationRule:function(entityArr){
                if (entityArr.length == 0) {
                    return
                }
                this.delAutomationRule( entityArr.join(","),Carousel.Dao.getChannel().id);
            },
            checkMultiAutomationRule: function (sendData, tableName) {
                var dataArr = $(tableName).getRowData();
                //.jqGrid('getData');
                var uniqueKey = "" + sendData.qipuId;
                var findSamekey = false;
                $.each(dataArr, function (i, element) {
                    if (JSON.parse(element.hiddenData).qipuId == uniqueKey) {
                        findSamekey = true;
                        return false;
                    }
                });
                return findSamekey;
            },
            prepareAutomationRuleData: function (element) {
                var sendObject = {};
                sendObject.fatherId = Carousel.Dao.getChannel().id;
                sendObject.showName = element.value;
                sendObject.channelTag = element.channelName;
                sendObject.qipuId = element.id;

                sendObject.copyrightEndTime = "";

                var queryMsg = "";
                if (element.copyrightEndTime == -100) {
                    sendObject.copyrightEndTime = "-100";
                } else if (element.copyrightEndTime != null && element.copyrightEndTime != "" && element.copyrightEndTime > 0) {
                    sendObject.copyrightEndTime = Carousel.Util.formatter.copyrightEndTime(element.copyrightEndTime);
                }
                //epg 收费状态(1：免费 2：收费)
                sendObject.bossStatus = 1;
                if (element.isPurchase !== "") {
                    sendObject.bossStatus = element.isPurchase === 1 ? 2 : 1
                }
                //epg 发布状态(1：未发布 2：已发布)
                sendObject.publishStatus = 2
                sendObject.totalNum = element.totalNum;
                sendObject.pageUrl = element.pageUrl;
                if (sendObject.pageUrl == null) {
                    sendObject.pageUrl = "";
                }
                sendObject.actualNum = parseInt($("input[name=actualNum]").val());
                return sendObject;
            },
            addAutomationRule: function (allowMulti) {
                var parent = $("#carouselAutoRuleView");
                var element = Carousel.Config.ruleSelectElement
                if (element == null) {
                    console.log("no element selected")
                    return;
                }
                var checkArr = [];
                checkArr.push({value: element.id + "", error: "不允许手动修改对象奇谱Id", type: "eq", other: parent.find("input[name=_" + parent.find("select[name=frontSuggestType]").val() + "]").attr("data-id") })
                if (!EpgWeb.Plugin.Validate.batchCheck(checkArr)) {
                    console.log("interrupt case check Fail")
                    return;
                }
                var sendObject = Carousel.Util.prepareAutomationRuleData(element);
                //开始
                var hasSame = Carousel.Util.checkMultiAutomationRule(sendObject)
                console.log("hasSame:" + hasSame);
                if (!allowMulti && hasSame) {
                    SystemDialog.queryConfirm("专辑《" + sendObject.showName + "》已存在，是否确认再次添加", function (flag) {
                        if (flag == true) {
                            Carousel.Util.addAutomationRule(true);
                        }
                    })
                    return;
                }

                var msg = [];
                if (element.hintMsgObj.missPPSClient) {
                    msg.push(Carousel.Config.ErrorMsg.PPS_CLIENT_MSG)
                }
                if (element.hintMsgObj.missQIYIClient) {
                    msg.push(Carousel.Config.ErrorMsg.QIYI_CLIENT_MSG);
                }
                if (element.hintMsgObj.missPPSRegion) {
                    msg.push(Carousel.Config.ErrorMsg.PPS_REGION_MSG);
                }
                if (element.hintMsgObj.missQIYIRegion) {
                    msg.push(Carousel.Config.ErrorMsg.QIYI_REGION_MSG);
                }
                if (msg.length > 0) {
                    SystemDialog.queryConfirm(msg.join("<br>"), function (flag) {
                        if (flag === true) {
                            $("#carouselAutoRuleView").find("button[name=addRule]").prop("disabled", "disabled");
                            var task = Carousel.Task.sendAddRuleTask(sendObject)
                            Carousel.ajaxManager.push(task.regName, task.options, null, true);
                            Carousel.ajaxManager.startLoad();
                        }
                    })
                } else {
                    $("#carouselAutoRuleView").find("button[name=addRule]").prop("disabled", "disabled");
                    var task = Carousel.Task.sendAddRuleTask(sendObject)
                    Carousel.ajaxManager.push(task.regName, task.options, null, true);
                    Carousel.ajaxManager.startLoad();
                }
            },
            changeStatusAutomationRule:function(execStatus){
                var sendData = { channelId: Carousel.Dao.getChannel().id  , execStatus: execStatus}
                Carousel.Dao.changeStatusAutomationRule( sendData,function(data){
                        if(data == null){
                            SystemDialog.queryAlert(data.msg);
                        }else if(data.code == "A00000"){
                        }else if( data.msg != null ){
                            SystemDialog.queryAlert(data.msg)
                        }
                    $("#ruleList").trigger("reloadGrid")
                } )
            }
            // automation rule end
        })


    }
);